#include <curl/curl.h>
#include "aibox.h"
#include "common.h"
#include "log.h"
#include "config.h"
#include <pthread.h>
#include "../cJSON/cJSON.h"

static CURL *curl = NULL;
static char *response = NULL;

#define AI_SERVER_URL "http://192.168.1.249:8000/api/analyze/seemideo/image/operations/recognize"
#define IMAGE_URL     "http://192.168.1.249:8999/pic/"
#define IMAGE_PATH    "/home/linaro/zhuke/httpfiles/pic/"

static size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
{
    size_t realsize = size * nmemb;
    char **response_ptr = (char **)userdata;

    // 扩展 response 的大小
    char *new_response = realloc(*response_ptr, strlen(*response_ptr) + realsize + 1);
    if (new_response == NULL) {
        fprintf(stderr, "Failed to allocate memory for response\n");
        return 0;  // 返回 0 表示错误
    }
    *response_ptr = new_response;

    // 将新数据追加到 response 中
    strncat(*response_ptr, ptr, realsize);
    return realsize;
}

void init_aibox_server(void)
{
    // 初始化 AI Box 服务器相关资源
    // 例如设置端口、加载配置等
    curl = curl_easy_init();
    if (!curl) {
        fprintf(stderr, "Failed to initialize CURL for AI Box server\n");
        exit(1);
    }
    response = malloc(1);
    if (!response) {
        fprintf(stderr, "Failed to allocate memory for AI Box response\n");
        curl_easy_cleanup(curl);
        exit(1);
    }
    response[0] = '\0';
    // 设置 AI Box 服务器的基本配置
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
    // curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

    printf("AI Box server initialized.\n");
}

bool send_picture_to_aibox(const char *file_name)
{
    char image_url[256];
    char image_path[256];
    char *json_data = NULL;
    char *json_str = NULL;
    cJSON *request = NULL;
    cJSON *json_response = NULL;
    struct curl_slist *headers = NULL;
    char error_buf[CURL_ERROR_SIZE] = {0};
    CURLcode res = CURLE_FAILED_INIT;
    int64_t start_time, end_time;
    start_time = get_current_time_in_milliseconds();

    /* 1. 构造图片 URL */
    snprintf(image_url, sizeof(image_url), "%s%s", IMAGE_URL, file_name);

    /* 1. 构造图片路径 */
    // snprintf(image_path, sizeof(image_path), "%s%s", IMAGE_PATH, file_name);

    /* 2. 创建 cJSON 请求体 */
    request = cJSON_CreateObject();
    if (request == NULL) {
        goto cleanup;
    }
    cJSON_AddNumberToObject(request, "recogType", 0);
    cJSON_AddStringToObject(request, "imageUrl", image_url);
    // cJSON_AddStringToObject(request, "filePath", image_path);

#if 0
    /* 3. 构造识别区域数组 */
    {
        // int16_t recogRegion[][2] = {
        //     {1261, 675}, {1215, 2055}, {2710, 2065}, {2622, 704}};
        int16_t recogRegion[] = {
            350, 400, 900, 900};
        cJSON *region_array = cJSON_CreateArray();
        if (region_array == NULL) {
            goto cleanup_request;
        }
        // for (size_t i = 0; i < sizeof(recogRegion) / sizeof(recogRegion[0]); i++) {
        //     cJSON *pt = cJSON_CreateArray();
        //     if (pt == NULL) {
        //         cJSON_Delete(region_array);
        //         goto cleanup_request;
        //     }
        //     cJSON_AddItemToArray(pt, cJSON_CreateNumber(recogRegion[i][0]));
        //     cJSON_AddItemToArray(pt, cJSON_CreateNumber(recogRegion[i][1]));
        //     cJSON_AddItemToArray(region_array, pt);
        // }
        for (size_t i = 0; i < sizeof(recogRegion) / sizeof(recogRegion[0]); i++) {
            cJSON *pt = cJSON_CreateNumber(recogRegion[i]);
            if (pt == NULL) {
                cJSON_Delete(region_array);
                goto cleanup_request;
            }
            cJSON_AddItemToArray(region_array, pt);
        }
        cJSON_AddItemToObject(request, "recogRegion", region_array);
        /* region_array 将由 request 一并管理，无需单独 delete */
    }
#endif

    /* 3. 打印请求体 */
    json_str = cJSON_Print(request);
    if (json_str == NULL) {
        fprintf(stderr, "Failed to print JSON request\n");
        goto cleanup_request;
    }
    printf("AI Box request: %s\n", json_str);
    free(json_str);

    /* 4. 序列化为紧凑 JSON 字符串 */
    json_data = cJSON_PrintUnformatted(request);
    if (json_data == NULL) {
        goto cleanup_request;
    }

    /* 5. 设置 HTTP 头 */
    headers = curl_slist_append(NULL, "Content-Type: application/json");
    headers = curl_slist_append(headers, "Accept: */*");
    if (headers == NULL) {
        goto cleanup_json;
    }
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

    /* 6. 设置请求参数 */
    curl_easy_setopt(curl, CURLOPT_URL, AI_SERVER_URL);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data);
    curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, error_buf);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L);

    /* 7. 执行 HTTP 请求 */
    res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        fprintf(stderr, "[PR] Request failed: %s\n", error_buf);
        goto cleanup_headers;
    }

    /* 8. 解析响应 */
    json_response = cJSON_Parse(response);
    if (json_response == NULL) {
        goto cleanup_headers;
    }
    /* 可按需处理 json_response 中的内容 */
    json_str = cJSON_Print(json_response);
    if (json_str == NULL) {
        fprintf(stderr, "Failed to print JSON response\n");
        goto cleanup_headers;
    }
    printf("AI Box response: %s\n", json_str);
    free(json_str);
    json_str = NULL;

    res = CURLE_OK;

cleanup_headers:
    if (headers) {
        curl_slist_free_all(headers);
    }
cleanup_json:
    free(json_data);
cleanup_request:
    cJSON_Delete(request);
cleanup_response:
    cJSON_Delete(json_response);
cleanup:
    end_time = get_current_time_in_milliseconds();
    printf("AI Box request time: %ld ms\n", end_time - start_time);
    return (res == CURLE_OK);
}

void *ai_box_thread(void *arg)
{
    // 初始化 AI Box 服务器
    init_aibox_server();

    // 持续运行 AI Box 服务器
    while (1) {
        // 处理 AI Box 相关逻辑
        // 例如接收图片、处理请求等
        send_picture_to_aibox("test_image3.jpeg");
        sleep(60);  // 模拟处理时间
    }

    return NULL;  // 线程结束时返回 NULL
}

pthread_t start_aibox_server(void)
{
    pthread_t aibox_thread_id;
    // 创建一个线程来运行 AI Box 服务器
    if (pthread_create(&aibox_thread_id, NULL, ai_box_thread, NULL) != 0) {
        perror("Thread creation failed");
        exit(1);
    }
    pthread_detach(aibox_thread_id);  // 分离线程，避免资源泄漏
    printf("AI Box server started.\n");
    return aibox_thread_id;
}
